package com.mrzhou.rabbit.producer;

import com.mrzhou.rabbit.constant.RabbitConstant;
import com.mrzhou.rabbit.entity.EsMqMessage;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Component;

import java.util.UUID;

/**
 * @author qiang.zhou
 */
@Component
@Slf4j
public class ElasticsearchProduct {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    private final RabbitTemplate.ConfirmCallback confirmCallback =  (correlationData, ack, cause) -> {
        if(!ack) {
            log.error("消息发送失败：correlationData: {},cause: {}", correlationData, cause);
        }
    };
    private final RabbitTemplate.ReturnCallback returnCallback = (message, replyCode, replyText, exchange, routingKey) -> {
        log.error("消息丢失: message: {}, exchange: {},routeKey: {},replyCode: {},replyText: {}", message, replyCode, replyText, exchange, routingKey);
    };

    public void send(EsMqMessage message) {
        // 构建回调返回的数据
        CorrelationData correlationData = new CorrelationData();
        // 生成消息ID
        correlationData.setId(UUID.randomUUID().toString());
        // 设置发送成功的回调方式
        rabbitTemplate.setConfirmCallback(confirmCallback);
        rabbitTemplate.setReturnCallback(returnCallback);
        rabbitTemplate.convertAndSend(RabbitConstant.ELASTICSEARCH_EXCHANGE, RabbitConstant.ELASTICSEARCH_QUEUE, message, correlationData);
    }


}
